package com.cq;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class AjaxUtil {

	/**
	 * 把数据写到前台，方便ajax调用
	 * 
	 * @param response
	 * @param message
	 */
	public static void writeString2Front(HttpServletResponse response,
			Object obj) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("CacheControl", "no-cache");

		PrintWriter print = null;
		try {
			print = response.getWriter();
			print.print(JSON.toJSONString(obj,
					SerializerFeature.DisableCircularReferenceDetect));
			print.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (print != null) {
				print.close();
			}
		}
	}
	
	
	/**
	 * 把数据写到前台，方便ajax调用
	 * 
	 * @param response
	 * @param message
	 */
	public static void writeStringFront(HttpServletResponse response,
			Object obj) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("CacheControl", "no-cache");

		PrintWriter print = null;
		try {
			print = response.getWriter();
			print.print(obj);
			print.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (print != null) {
				print.close();
			}
		}
	}


	/**
	 * ajax调用(带时间转换)
	 * 
	 * @param response
	 * @param obj
	 * @param DateFormat
	 *            ("YYYY-MM-dd")
	 */
	public static void writeStringDateFormat2Front(
			HttpServletResponse response, Object obj, String DateFormat) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("CacheControl", "no-cache");

		PrintWriter print = null;
		try {
			print = response.getWriter();
			print.print(JSON.toJSONStringWithDateFormat(obj, DateFormat,
					SerializerFeature.WriteDateUseDateFormat));
			print.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (print != null) {
				print.close();
			}
		}
	}

}
